import type { FC, MouseEvent as ReactMouseEvent } from "react";
import { useRef, useState, useEffect } from "react";
// 导入新的 ContextMenu 组件替换 Popover
import ContextMenu, { useContextMenu } from "./ui/ContextMenu";
import type { CreateSessionRequestResponseType } from "../services/chat/createSession";
import type { ChatMessage } from "../types/chat";
import { formatDateTime } from "../utils/dateFormat";
import alertService from "../utils/alertService"; // 导入alertService

// 为 window 对象添加自定义属性
declare global {
  interface Window {
    lastContextMenuPosition?: { x: number; y: number };
    lastTouchPosition?: { x: number; y: number };
  }
}

// 定义聊天历史项的类型
interface ChatHistoryItem {
  id: string;
  title: string;
  date: string;
  messages: ChatMessage[];
  modelId: string; // 添加模型ID字段，这里使用accessCode
}

// 定义会话分组
interface ChatGroup {
  title: string;
  chats: CreateSessionRequestResponseType[];
}

interface SidebarProps {
  onNewChat?: () => void;
  sessionHistoryItem?: CreateSessionRequestResponseType[];
  chatHistory?: ChatHistoryItem[];
  onSelectChat?: (id: string) => void;
  activeChat?: string | null;
  onRenameChat?: (id: string, newTitle: string) => void;
  onDeleteChat?: (id: string) => void;
  isOpen?: boolean; // 控制移动端是否显示
  onClose?: () => void; // 移动端关闭侧边栏
  isResponding?: boolean; // 添加AI响应状态属性
  onPcSidebarToggle?: (collapsed: boolean) => void; // PC端侧边栏折叠状态回调
}

const Sidebar: FC<SidebarProps> = ({
  sessionHistoryItem = [],
  onSelectChat,
  activeChat = null,
  onRenameChat,
  onDeleteChat,
  isOpen = false,
  onClose,
  onNewChat,
  isResponding = false, // 默认为false
  onPcSidebarToggle,
}) => {
  // 使用新的 useContextMenu hook 替换原来的右键菜单状态
  const {
    open: contextMenuOpen,
    positionX,
    positionY,
    handleContextMenu,
    closeContextMenu,
  } = useContextMenu();

  // 添加状态变量来跟踪上下文菜单是否打开
  const [isContextMenuOpen, setIsContextMenuOpen] = useState(false);

  // 添加PC端侧边栏折叠状态
  const [isPcSidebarCollapsed, setIsPcSidebarCollapsed] = useState(false);

  // 当前右键点击的聊天ID
  const [currentChatId, setCurrentChatId] = useState<string>("");

  // 添加折叠状态跟踪
  const [collapsedChats, setCollapsedChats] = useState<Set<string>>(new Set());

  // 添加折叠状态跟踪（会话组）
  const [collapsedGroups, setCollapsedGroups] = useState<Set<string>>(
    new Set()
  );

  // 重命名状态
  const [isRenaming, setIsRenaming] = useState(false);
  const [newTitle, setNewTitle] = useState("");
  const activeButtonRef = useRef<HTMLButtonElement>(null);
  const longPressTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const sidebarRef = useRef<HTMLDivElement>(null);

  // 存储会话项按钮的引用映射
  const chatButtonRefs = useRef<Map<string, HTMLButtonElement | null>>(
    new Map()
  );

  // PC端侧边栏折叠/展开处理函数
  const togglePcSidebar = () => {
    const newState = !isPcSidebarCollapsed;
    setIsPcSidebarCollapsed(newState);
    // 保存侧边栏状态到localStorage，以便页面刷新后保持相同状态
    localStorage.setItem("sidebarCollapsed", newState.toString());
    // 通知父组件状态变化
    if (onPcSidebarToggle) {
      onPcSidebarToggle(newState);
    }
  };

  // 页面加载时从localStorage读取侧边栏状态
  useEffect(() => {
    const savedState = localStorage.getItem("sidebarCollapsed");
    if (savedState === "true") {
      setIsPcSidebarCollapsed(true);
    }
  }, []);

  // 监听上下文菜单状态变化
  useEffect(() => {
    setIsContextMenuOpen(contextMenuOpen);
  }, [contextMenuOpen]);

  // 添加触摸事件监听，记录最后的触摸位置
  useEffect(() => {
    const handleTouchStart = (e: TouchEvent) => {
      if (e.touches && e.touches[0]) {
        window.lastTouchPosition = {
          x: e.touches[0].clientX,
          y: e.touches[0].clientY,
        };
      }
    };

    document.addEventListener("touchstart", handleTouchStart);
    return () => {
      document.removeEventListener("touchstart", handleTouchStart);
    };
  }, []);

  // 合并API会话和本地会话
  // 使用两种聊天历史: API加载的历史和本地创建的历史
  // 并按最新的更新时间排序，确保新会话在顶部显示
  const allChats = [
    ...sessionHistoryItem,
    // 不再合并本地会话
  ].sort((a, b) => {
    try {
      const dateA = new Date(a.updateTime).getTime();
      const dateB = new Date(b.updateTime).getTime();
      // 降序排列，最新的在前
      return dateB - dateA;
    } catch {
      // 如果转换失败，保持原有顺序
      return 0;
    }
  });

  // 当会话列表或活动会话变化时记录日志
  useEffect(() => {
    if (activeChat) {
      const activeSession = sessionHistoryItem.find(
        (chat) => chat.id === activeChat
      );
      if (activeSession) {
        console.log("Sidebar - 活动会话名称:", activeSession.sessionName);
      } else {
        console.warn("Sidebar - 活动会话不在列表中:", activeChat);
      }
    }
  }, [sessionHistoryItem, activeChat]);

  // 监听点击外部关闭侧边栏
  useEffect(() => {
    const handleClickOutside = (event: Event) => {
      // 如果上下文菜单打开，不关闭侧边栏
      if (isContextMenuOpen) {
        console.log("上下文菜单打开中，不关闭侧边栏");
        return;
      }

      // 只在移动端（窗口宽度小于768px）且侧边栏打开时处理
      if (
        isOpen &&
        sidebarRef.current &&
        !sidebarRef.current.contains(event.target as Node) &&
        window.innerWidth < 768
      ) {
        console.log("点击侧边栏外部，关闭侧边栏");
        if (onClose) onClose();
      }
    };

    // 只在侧边栏打开时添加事件监听器
    if (isOpen) {
      document.addEventListener("mousedown", handleClickOutside);
      document.addEventListener("touchend", handleClickOutside);
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
      document.removeEventListener("touchend", handleClickOutside);
    };
  }, [isOpen, onClose, isContextMenuOpen]);

  const handleSelectChat = (id: string) => {
    // 新增：如果AI正在响应中，禁止切换会话
    if (isResponding) {
      alertService.warning("AI正在生成回复，请等待完成后再切换会话");
      return;
    }

    if (onSelectChat) {
      onSelectChat(id);
    }
    // 在移动端选择聊天后自动关闭侧边栏
    if (onClose && window.innerWidth < 768) {
      onClose();
    }
  };

  // 计算菜单位置 - 在会话项的右下方
  const calculateMenuPosition = (chatId: string): { x: number; y: number } => {
    // 获取会话项按钮元素
    const buttonElement = chatButtonRefs.current.get(chatId);

    if (buttonElement) {
      // 获取元素的位置和尺寸
      const rect = buttonElement.getBoundingClientRect();

      // 计算右下角的位置
      const x = rect.right - 10; // 稍微向左偏移一点
      const y = rect.bottom - 5; // 稍微向上偏移一点

      return { x, y };
    }

    // 如果找不到元素，使用默认位置
    console.warn(`找不到会话项 ${chatId} 的元素，使用默认位置`);
    return window.lastTouchPosition || { x: 0, y: 0 };
  };

  // 处理右键点击
  const handleChatContextMenu = (e: ReactMouseEvent, chatId: string) => {
    e.preventDefault(); // 阻止默认右键菜单
    e.stopPropagation(); // 阻止事件冒泡

    // 设置当前操作的聊天ID
    setCurrentChatId(chatId);

    console.log("右键菜单触发:", chatId, e.clientX, e.clientY);

    // 直接使用原始事件对象，不再计算位置
    handleContextMenu(e);
  };

  // 处理移动端长按
  const handleTouchStart = (chatId: string, e: React.TouchEvent) => {
    // 阻止事件冒泡，防止触发侧边栏关闭
    e.stopPropagation();

    longPressTimeoutRef.current = setTimeout(() => {
      setCurrentChatId(chatId);

      // 计算菜单位置 - 在会话项的右下方
      const menuPosition = calculateMenuPosition(chatId);

      // 保存位置到全局变量
      window.lastContextMenuPosition = menuPosition;

      // 使用计算的位置显示上下文菜单
      handleContextMenu({
        clientX: menuPosition.x,
        clientY: menuPosition.y,
        preventDefault: () => {},
        stopPropagation: () => {},
      } as React.MouseEvent<HTMLButtonElement>);
    }, 500); // 长按时间阈值
  };

  const handleTouchEnd = (e: React.TouchEvent) => {
    // 阻止事件冒泡，防止触发侧边栏关闭
    e.stopPropagation();

    if (longPressTimeoutRef.current) {
      clearTimeout(longPressTimeoutRef.current);
      longPressTimeoutRef.current = null;
    }
  };

  const handleTouchMove = (e: React.TouchEvent) => {
    // 阻止事件冒泡，防止触发侧边栏关闭
    e.stopPropagation();

    if (longPressTimeoutRef.current) {
      clearTimeout(longPressTimeoutRef.current);
      longPressTimeoutRef.current = null;
    }
  };

  // 处理重命名会话
  const handleRenameChat = () => {
    // 先关闭上下文菜单
    closeContextMenu();

    // 找到当前聊天的标题
    const chat = allChats.find((chat) => chat.id === currentChatId);
    if (!chat) {
      console.error("未找到要重命名的会话:", currentChatId);
      return;
    }

    // 设置新标题为当前标题，并进入重命名状态
    setNewTitle(chat.sessionName || "");
    setIsRenaming(true);

    // 确保重命名状态被正确设置
    setTimeout(() => {
      console.log("重命名状态:", isRenaming, "当前聊天ID:", currentChatId);
    }, 100);
  };

  // 提交重命名
  const submitRename = () => {
    console.log("提交重命名:", currentChatId, newTitle);

    if (onRenameChat && currentChatId && newTitle.trim()) {
      // 调用父组件提供的重命名方法
      onRenameChat(currentChatId, newTitle.trim());

      // 重置状态
      setIsRenaming(false);
      setNewTitle("");
    }
  };

  // 处理删除会话
  const handleDeleteChat = () => {
    closeContextMenu();
    if (onDeleteChat && currentChatId) {
      onDeleteChat(currentChatId);
      console.log("删除完成");
    }
  };

  // 处理折叠/展开会话
  const toggleCollapseChat = (chatId: string, e: ReactMouseEvent) => {
    e.stopPropagation(); // 阻止事件冒泡，防止触发选择聊天

    setCollapsedChats((prevState) => {
      const newState = new Set(prevState);
      if (newState.has(chatId)) {
        newState.delete(chatId);
      } else {
        newState.add(chatId);
      }
      return newState;
    });
  };

  // 处理折叠/展开会话组
  const toggleCollapseGroup = (groupTitle: string, e: ReactMouseEvent) => {
    e.stopPropagation(); // 阻止事件冒泡

    setCollapsedGroups((prevState) => {
      const newState = new Set(prevState);
      if (newState.has(groupTitle)) {
        newState.delete(groupTitle);
      } else {
        newState.add(groupTitle);
      }
      return newState;
    });
  };

  // 会话分组函数
  const groupChats = (
    chats: CreateSessionRequestResponseType[]
  ): ChatGroup[] => {
    // 如果没有会话，返回空数组
    if (chats.length === 0) return [];

    // 用于存储分组结果
    const groups: Record<string, CreateSessionRequestResponseType[]> = {};

    // 获取今天和昨天的日期（使用本地时区）
    const now = new Date();
    const today = new Date(
      now.getFullYear(),
      now.getMonth(),
      now.getDate()
    ).getTime();
    const yesterday = new Date(today - 86400000).getTime();

    // 遍历所有会话，根据日期进行分组
    chats.forEach((chat) => {
      try {
        // 解析会话更新时间，并转换为本地日期的午夜时间戳用于比较
        const chatDate = new Date(chat.updateTime);
        const chatDateMidnight = new Date(
          chatDate.getFullYear(),
          chatDate.getMonth(),
          chatDate.getDate()
        ).getTime();

        // 确定组标题
        let groupTitle: string;
        if (chatDateMidnight === today) {
          groupTitle = "今天";
        } else if (chatDateMidnight === yesterday) {
          groupTitle = "昨天";
        } else {
          // 使用本地化的日期格式
          groupTitle = chatDate.toLocaleDateString("zh-CN", {
            year: "numeric",
            month: "long",
            day: "numeric",
          });

          // 如果本地化失败，使用备用格式
          if (groupTitle === "Invalid Date") {
            const year = chatDate.getFullYear();
            const month = chatDate.getMonth() + 1;
            const day = chatDate.getDate();
            groupTitle = `${year}年${month}月${day}日`;
          }
        }

        // 将会话添加到相应的组
        if (!groups[groupTitle]) {
          groups[groupTitle] = [];
        }
        groups[groupTitle].push(chat);
      } catch (error) {
        console.error(`会话日期解析错误 (ID: ${chat.id}):`, error);
        // 如果日期解析出错，放入"其他"组
        const groupTitle = "其他";
        if (!groups[groupTitle]) {
          groups[groupTitle] = [];
        }
        groups[groupTitle].push(chat);
      }
    });

    // 将分组结果转换为数组格式
    const groupArray: ChatGroup[] = Object.keys(groups).map((title) => ({
      title,
      chats: groups[title],
    }));

    // 按特定顺序排序（今天、昨天，然后是其他日期）
    return groupArray.sort((a, b) => {
      if (a.title === "今天") return -1;
      if (b.title === "今天") return 1;
      if (a.title === "昨天") return -1;
      if (b.title === "昨天") return 1;
      return 0;
    });
  };

  const renderTitleBar = (isMobile = false) => (
    <div
      className={`${
        isPcSidebarCollapsed && !isMobile ? "justify-center" : "justify-between"
      } px-4 py-3 border-b border-gray-200 dark:border-gray-700 flex items-center`}
    >
      {/* 只在展开状态下或移动端显示标题 */}
      {(!isPcSidebarCollapsed || isMobile) && (
        <h3 className="text-sm font-semibold text-gray-600 dark:text-gray-300 uppercase tracking-wider">
          对话历史
        </h3>
      )}

      <div className="flex items-center">
        {/* PC端折叠/展开按钮 - 仅在PC端非折叠状态下显示 */}
        {!isPcSidebarCollapsed && !isMobile && (
          <button
            onClick={togglePcSidebar}
            className="hidden md:flex items-center justify-center w-7 h-7 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-full transition-all duration-200"
            aria-label="折叠侧边栏"
            title="折叠侧边栏"
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="h-5 w-5"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M11 19l-7-7 7-7m8 14l-7-7 7-7"
              />
            </svg>
          </button>
        )}

        {/* 移动端关闭按钮 - 只在移动端显示 */}
        {isMobile && (
          <button
            onClick={onClose}
            className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="h-5 w-5"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          </button>
        )}
      </div>
    </div>
  );

  const renderChatList = () => {
    if (allChats.length === 0) {
      return (
        <div className="flex flex-col items-center justify-center h-full py-10 text-gray-500 dark:text-gray-400">
          <svg
            xmlns="http://www.w3.org/2000/svg"
            className="h-12 w-12 mb-2"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
            />
          </svg>
          <p>暂无会话记录</p>
          <p className="text-sm mt-1">点击"新建会话"开始聊天</p>
        </div>
      );
    }

    // 获取分组后的会话
    const chatGroups = groupChats(allChats);

    return (
      <div className="flex-1 overflow-y-auto py-2 min-h-0">
        <div className="space-y-3 px-2">
          {chatGroups.map((group) => (
            <div key={group.title} className="mb-2">
              {/* 组标题与折叠控制 */}
              <div
                className="flex items-center justify-between px-2 py-1 text-sm font-medium text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded cursor-pointer"
                onClick={(e) => toggleCollapseGroup(group.title, e)}
              >
                <span>{group.title}</span>
                <button
                  className="p-1 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300"
                  aria-label={
                    collapsedGroups.has(group.title) ? "展开组" : "折叠组"
                  }
                  onClick={(e) => toggleCollapseGroup(group.title, e)}
                >
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    className={`h-4 w-4 transition-transform duration-200 ${
                      collapsedGroups.has(group.title)
                        ? "transform rotate-180"
                        : ""
                    }`}
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M19 9l-7 7-7-7"
                    />
                  </svg>
                </button>
              </div>

              {/* 组内会话列表 */}
              {!collapsedGroups.has(group.title) && (
                <div className="space-y-1 mt-1 pl-1">
                  {group.chats.map((chat) => (
                    <div
                      key={chat.id}
                      className="relative rounded-lg overflow-hidden"
                    >
                      {isRenaming && chat.id === currentChatId ? (
                        <div className="p-2 bg-white dark:bg-gray-800 rounded-lg">
                          <input
                            type="text"
                            value={newTitle}
                            onChange={(e) => setNewTitle(e.target.value)}
                            onKeyDown={(e) => {
                              if (e.key === "Enter") {
                                submitRename();
                              } else if (e.key === "Escape") {
                                setIsRenaming(false);
                                setNewTitle("");
                              }
                            }}
                            className="w-full px-3 py-2 text-sm border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                            placeholder="输入新标题..."
                            autoFocus
                          />
                          <div className="flex justify-end mt-2 space-x-2">
                            <button
                              onClick={() => {
                                setIsRenaming(false);
                                setNewTitle("");
                              }}
                              className="px-2 py-1 text-xs text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded"
                            >
                              取消
                            </button>
                            <button
                              onClick={submitRename}
                              className="px-2 py-1 text-xs text-white bg-blue-500 hover:bg-blue-600 rounded"
                            >
                              保存
                            </button>
                          </div>
                        </div>
                      ) : (
                        <div
                          className={`w-full rounded-lg text-sm ${
                            activeChat === chat.id
                              ? "bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-l-2 border-blue-500"
                              : "text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700"
                          } ${
                            isResponding ? "opacity-50 cursor-not-allowed" : ""
                          }`}
                        >
                          <div className="flex items-center justify-between">
                            <button
                              ref={(el) => {
                                chatButtonRefs.current.set(chat.id, el);
                                if (chat.id === currentChatId) {
                                  activeButtonRef.current = el;
                                }
                              }}
                              onClick={() => handleSelectChat(chat.id)}
                              onContextMenu={(e) =>
                                handleChatContextMenu(e, chat.id)
                              }
                              onTouchStart={(e) => handleTouchStart(chat.id, e)}
                              onTouchEnd={handleTouchEnd}
                              onTouchMove={handleTouchMove}
                              className="flex-1 text-left px-4 py-3"
                              disabled={isResponding}
                              style={{
                                WebkitTapHighlightColor: "rgba(0,0,0,0)", // 移除Safari上的默认点击高亮
                              }}
                            >
                              <div className="flex flex-col">
                                <span className="font-medium truncate">
                                  {chat.sessionName || "新会话"}
                                </span>
                              </div>
                            </button>
                            <button
                              onClick={(e) => toggleCollapseChat(chat.id, e)}
                              className="px-3 py-3 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300 transition-colors duration-150"
                              aria-label={
                                collapsedChats.has(chat.id)
                                  ? "展开会话"
                                  : "折叠会话"
                              }
                            >
                              <svg
                                xmlns="http://www.w3.org/2000/svg"
                                className={`h-5 w-5 transition-transform duration-200 ${
                                  collapsedChats.has(chat.id)
                                    ? "transform rotate-180"
                                    : ""
                                }`}
                                fill="none"
                                viewBox="0 0 24 24"
                                stroke="currentColor"
                              >
                                <path
                                  strokeLinecap="round"
                                  strokeLinejoin="round"
                                  strokeWidth={2}
                                  d="M19 9l-7 7-7-7"
                                />
                              </svg>
                            </button>
                          </div>
                          {/* 折叠内容区域 */}
                          {!collapsedChats.has(chat.id) && (
                            <div className="px-4 pb-2 text-xs text-gray-500 dark:text-gray-400">
                              <div className="border-t border-gray-200 dark:border-gray-700 pt-2 mt-1 space-y-1">
                                <div className="flex items-center">
                                  <span className="font-medium mr-1">
                                    创建时间:
                                  </span>
                                  <span>{formatDateTime(chat.updateTime)}</span>
                                </div>
                                <div className="flex items-center">
                                  <span className="font-medium mr-1">ID:</span>
                                  <span className="truncate">{chat.id}</span>
                                </div>
                              </div>
                            </div>
                          )}
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              )}
            </div>
          ))}
        </div>
      </div>
    );
  };

  const renderNewChatButton = () => (
    <div className="px-4 py-3 border-t border-gray-200 dark:border-gray-700 sticky bottom-0 bg-white dark:bg-gray-800 mt-auto">
      <button
        onClick={onNewChat}
        className="flex items-center justify-center w-full py-2.5 px-4 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors duration-150"
        aria-label="新建对话"
        disabled={isResponding}
      >
        <svg
          xmlns="http://www.w3.org/2000/svg"
          className="h-4 w-4 mr-2"
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M12 4v16m8-8H4"
          />
        </svg>
        <span className={isResponding ? "opacity-50" : ""}>新建对话</span>
      </button>
    </div>
  );

  return (
    <>
      {/* 移动端背景遮罩层 - 只在侧边栏打开时显示 */}
      {isOpen && (
        <div
          className="fixed inset-0 bg-black bg-opacity-50 z-40 md:hidden"
          onClick={onClose}
          style={{
            animation: "fadeIn 200ms ease-out",
          }}
        />
      )}

      {/* 侧边栏主体 */}
      <div
        ref={sidebarRef}
        className={`fixed md:relative top-0 left-0 h-full bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 flex flex-col z-50 ${
          isOpen ? "translate-x-0" : "-translate-x-full md:translate-x-0"
        } ${
          isPcSidebarCollapsed
            ? "md:w-12 md:overflow-visible sidebar-collapsed"
            : "w-[85vw] max-w-xs md:w-64 sidebar-expanded"
        }`}
        style={{
          boxShadow: isPcSidebarCollapsed
            ? "0 4px 6px -1px rgba(0, 0, 0, 0.05)"
            : isOpen
            ? "0 0 15px rgba(0, 0, 0, 0.1)"
            : "",
          transition:
            "width 350ms cubic-bezier(0.4, 0, 0.2, 1), transform 250ms cubic-bezier(0.16, 1, 0.3, 1), box-shadow 350ms cubic-bezier(0.4, 0, 0.2, 1)",
          height: "100%", // 确保高度为100%
          display: "flex",
          flexDirection: "column",
        }}
      >
        {/* 移动端始终显示标题栏 */}
        <div className="block md:hidden">{renderTitleBar(true)}</div>

        {/* PC端根据折叠状态决定是否显示标题栏 */}
        <div className="hidden md:block">
          {!isPcSidebarCollapsed && renderTitleBar(false)}
        </div>

        {/* 移动端始终显示聊天列表和新建按钮 */}
        <div className="block md:hidden flex-1 flex flex-col min-h-0">
          {renderChatList()}
          {renderNewChatButton()}
        </div>

        {/* PC端只在非折叠状态下显示聊天列表和新建按钮 */}
        {!isPcSidebarCollapsed && (
          <div className="hidden md:flex md:flex-1 md:flex-col min-h-0">
            {renderChatList()}
            {renderNewChatButton()}
          </div>
        )}

        {/* 折叠状态下只显示展开图标 - 仅PC端 */}
        {isPcSidebarCollapsed && (
          <div className="hidden md:flex flex-col items-center justify-center h-full">
            <button
              onClick={togglePcSidebar}
              className="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-full transition-all duration-200"
              aria-label="展开侧边栏"
              title="展开侧边栏"
              style={{
                animation: "fadeIn 0.5s ease-out",
              }}
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                className="h-5 w-5"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                style={{
                  transition: "transform 200ms ease",
                }}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M13 5l7 7-7 7"
                />
              </svg>
            </button>
          </div>
        )}
      </div>

      {/* 使用新的 ContextMenu 组件替代原来的 ChatContextMenu 组件 */}
      <ContextMenu
        open={contextMenuOpen}
        onClose={closeContextMenu}
        positionX={positionX}
        positionY={positionY}
        items={[
          {
            id: "rename",
            label: "重命名会话",
            icon: (
              <svg
                xmlns="http://www.w3.org/2000/svg"
                className="h-4 w-4"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"
                />
              </svg>
            ),
            onClick: handleRenameChat,
          },
          {
            id: "delete",
            label: "删除会话",
            icon: (
              <svg
                xmlns="http://www.w3.org/2000/svg"
                className="h-4 w-4"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
                />
              </svg>
            ),
            onClick: handleDeleteChat,
            color: "error",
          },
        ]}
      />

      {/* 添加CSS动画关键帧 */}
      <style>{`
        @keyframes fadeIn {
          from { opacity: 0; }
          to { opacity: 1; }
        }
        
        @keyframes slideInLeft {
          from { transform: translateX(-100%); }
          to { transform: translateX(0); }
        }
        
        /* 移动端侧边栏进入动画 */
        @media (max-width: 768px) {
          .sidebar-expanded {
            animation: slideInLeft 250ms cubic-bezier(0.16, 1, 0.3, 1);
          }
        }
        
        /* 修复滚动区域样式 */
        .sidebar-expanded .overflow-y-auto::-webkit-scrollbar {
          width: 4px;
        }
        
        .sidebar-expanded .overflow-y-auto::-webkit-scrollbar-track {
          background: transparent;
        }
        
        .sidebar-expanded .overflow-y-auto::-webkit-scrollbar-thumb {
          background-color: rgba(156, 163, 175, 0.5);
          border-radius: 20px;
        }
        
        /* 暗色模式滚动条 */
        .dark .sidebar-expanded .overflow-y-auto::-webkit-scrollbar-thumb {
          background-color: rgba(75, 85, 99, 0.5);
        }
      `}</style>
    </>
  );
};

export default Sidebar;
